/**
 * @(#)BasePDBiz.java 1.0 2013/9/4
 * Copyright 2013 PD, Inc. All rights reserved.
 */
package cn.broadin.app.hotel.bz;



import cn.broadin.app.hotel.MainActivity;
import cn.broadin.app.hotel.dialog.CustomProgressDialog;
import cn.broadin.app.hotel.stb.IPDAPK;
import cn.broadin.app.hotel.stb.IPDDataAccess;
import cn.broadin.app.hotel.stb.IPDMediaPlay;
import cn.broadin.app.hotel.stb.IPDSmartCard;
import cn.broadin.app.hotel.stb.IPDSysSetting;
import cn.broadin.app.hotel.stb.IPDVideoPlayer;

import android.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

/**
 * BasePDBiz PD应用通用接口
 * @author fenghui
 *
 */
public abstract class BasePDBiz {
	private static final String TAG = "BasePDBiz";			//log tag
	public Activity context = null;								//Activity对象
	public WebView webView = null;								//Webview对象
	private CustomProgressDialog dialog = null;					//加载提示框
	
	public BasePDBiz(Activity ctx, WebView wv) {
		this.context = ctx;
		this.webView = wv;
	}
	
	
	
	 
	@SuppressLint({ "SetJavaScriptEnabled", "JavascriptInterface" }) 
	public void setWebViewInfo(String url, String dataHost, String dataPort) {
		webView.setInitialScale(100);
        webView.setVerticalScrollBarEnabled(false);
		webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
		webView.setBackgroundColor(Color.BLACK);
		WebSettings webSettings = webView.getSettings();
		webSettings.setAllowFileAccess(true);							// 设置允许访问文件数据
		webSettings.setJavaScriptEnabled(true);							// 设置支持脚本
		webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
		webSettings.setUseWideViewPort(true);
		webSettings.setLoadWithOverviewMode(true);
		// 处理分辨率显示问题
		int screenDensity = context.getResources().getDisplayMetrics().densityDpi;
		WebSettings.ZoomDensity zoomDensity = WebSettings.ZoomDensity.FAR;
		switch (screenDensity) {
		case DisplayMetrics.DENSITY_LOW:
			zoomDensity = WebSettings.ZoomDensity.CLOSE;
			break;
		case DisplayMetrics.DENSITY_MEDIUM:
			zoomDensity = WebSettings.ZoomDensity.MEDIUM;
			break;
		case DisplayMetrics.DENSITY_HIGH:
			zoomDensity = WebSettings.ZoomDensity.FAR;
			break;
		}
		webSettings.setDefaultZoom(zoomDensity);
		webView.requestFocus();
		//添加浏览器接口
		webView.addJavascriptInterface(getDataAccess(), "DataAccess");
		webView.addJavascriptInterface(getMediaPlay(), "MediaPlayer");
		webView.addJavascriptInterface(getSmartCard(), "CA");
		webView.addJavascriptInterface(getAPK(), "APK");
		webView.addJavascriptInterface(new LogTest(), "LogTest");
		webView.addJavascriptInterface(getVideoPlaer(), "videoPlayer");
		IPDSysSetting sysSetting = getSysSetting();
		//Log.d("dyhsetWebViewInfo:","url = " + url + " data_host = " + dataHost + " data_port = "+ dataPort);
		sysSetting.setEnv("data_host", dataHost);//添加主机地址至应用全局变量，用于web应用访问数据接口
		sysSetting.setEnv("data_port", dataPort);//添加主机端口至应用全局变量，用于web应用访问数据接口
		sysSetting.setEnv("back_url", url);//添加当前打开页面地址至应用全局变量
		//sysSetting.setEnv("room_id", "" + MainActivity.roomID);//添加房号id至应用全局变量
		sysSetting.setEnv("marquee_text", "" + MainActivity.marqueeText);//添加滚动信息至应用全局变量
		sysSetting.setEnv("ProjectName", MainActivity.ProjectName);   //添加Web应用项目名称至全局变量
		webView.addJavascriptInterface(sysSetting, "SysSetting");
		webView.setWebViewClient(wvc);
		webView.setWebChromeClient(new WebChromeClient() {  
		    @Override  
		    public boolean onJsAlert(WebView view, String url, String message, final android.webkit.JsResult result)  
		    {  
		        new AlertDialog.Builder(context)  
		            .setTitle("JS alert")  
		            .setMessage(message)  
		            .setPositiveButton(R.string.ok,  
		                    new AlertDialog.OnClickListener()  
		                    {  
		            			@Override
		                        public void onClick(DialogInterface dialog, int which)  
		                        {  
		                            result.confirm();  
		                        }
		                    })  
		            .setCancelable(false)  
		            .create()  
		            .show();  
		  
		        return true;  
		    };  
		});  
		//应用默认url
		//String defaultUrl = ApplicationFactory.getApplication().APP_DEFAULTURL("") + PDUtils.getInstance().getMacAddress(context, false);
		//ApplicationFactory.getApplication().APP_DEFAULTURL(defaultUrl);
		Log.i(TAG, "load page url:" + url);
		webView.loadUrl(url);
	}
	
	//WebViewClient 对象
	WebViewClient wvc = new WebViewClient(){
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			return super.shouldOverrideUrlLoading(view, url);
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			Log.i(TAG, "DYH load url:" + url);
			if(dialog == null) {
				dialog = CustomProgressDialog.createDialog(context);
				dialog.setMessage("加载中,请稍候...");
			}
			dialog.show();
			super.onPageStarted(view, url, favicon);
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			if(dialog != null) {
				dialog.dismiss();
			}
			super.onPageFinished(view, url);
		}

		@Override
		public void onLoadResource(WebView view, String url) {
			super.onLoadResource(view, url);
		}

		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			Log.d("caolm:","page error");
			Log.d("caolm:","errorCode=" + errorCode);
			view.stopLoading();
			view.clearView();
			view.loadUrl("file:///android_asset/error.htm");
			//super.onReceivedError(view, errorCode, description, failingUrl);
		}
	};
	
	/**
	 * 获取javascript提供给webview的DataAccess对象
	 * @return
	 */
	
	public abstract IPDDataAccess getDataAccess();
	
	/**
	 * 获取javascript提供给webview的MediaPlayer对象
	 * @return
	 */
	
	public abstract IPDMediaPlay getMediaPlay();
	
	/**
	 * 获取javascript提供给webview的CA对象
	 * @return
	 */
	
	public abstract IPDSmartCard getSmartCard();
	
	/**
	 * 获取javascript提供给webview的SysSetting对象
	 * @return
	 */
	
	public abstract IPDSysSetting getSysSetting();
	
	/**
	 * 获取javascript提供给webview的openAPK对象
	 * @return
	 */
	
	public abstract IPDAPK getAPK();
	
	public class LogTest {
		
		@JavascriptInterface
    	public void show(String str) {
    		Log.d("webView log : ", str);
    	}
    }
	
	/**
	 * 获取javascript提供给webview的videoPlayer对象
	 * @return
	 */
	public abstract IPDVideoPlayer getVideoPlaer();
	
	/**
	 * 退出应用程序
	 */
	public void exitApp(){
		Log.d("caolm:","exitApp");
		this.context.finish();
		System.exit(0);
	}
	
	/**
	 * 机顶盒键值响应
	 * @return
	 */
	public void grabEvent(KeyEvent event) {
		if(event.getAction() == KeyEvent.ACTION_DOWN) {
			int keyCode = event.getKeyCode();
			Log.i(TAG, "grabEvent keycode is : " + keyCode);
			int code = 0;
			switch (keyCode) {
			case KeyEvent.KEYCODE_DPAD_CENTER:	//enter
				code = keyCode - 10;
				break;
			case KeyEvent.KEYCODE_DPAD_UP:		//up
				code = keyCode - 18;
				break;
			case KeyEvent.KEYCODE_DPAD_DOWN:	//down
				code = keyCode - 18;
				break;
			case KeyEvent.KEYCODE_DPAD_LEFT:	//left
				code = keyCode - 18;
				break;
			case KeyEvent.KEYCODE_DPAD_RIGHT:	//right
				code = keyCode - 18;
				break;
			case 66:
				code = keyCode - 53;			//enter
				break;
			case 111:							//back						
				code = 340;
				break;
			case KeyEvent.KEYCODE_0:			//数字键
			case KeyEvent.KEYCODE_1:
			case KeyEvent.KEYCODE_2:
			case KeyEvent.KEYCODE_3:
			case KeyEvent.KEYCODE_4:
			case KeyEvent.KEYCODE_5:
			case KeyEvent.KEYCODE_6:
			case KeyEvent.KEYCODE_7:
			case KeyEvent.KEYCODE_8:
			case KeyEvent.KEYCODE_9:
				code = keyCode + 41;
				break;
			}
			if(code != 0) {
				Log.i(TAG, "javascript:grabEvent(" + code + ")");
				webView.loadUrl("javascript:grabEvent(" + code + ")");
			}
		}
	}
}